<?php
namespace app\admin\controller;

use app\model\questionnaireModel;
use app\model\scoreModel;
use app\model\usersModel;
use think\facade\Request;
use think\facade\Validate;
use think\facade\View;

Class score {
    public function index()
    {
        $scoreList = scoreModel::select();
        foreach ($scoreList as &$value){
            $title_id = questionnaireModel::find($value['title_id']);
            $value['ques_title'] = $title_id['title'];
            $user_id = usersModel::find($value['user_id']);
            $value['user_name'] = $user_id['user_name'];
//            $sum = scoreModel::sum($value['ques_one'],
//                $value['ques_two'],$value['ques_three'],
//                $value['ques_four'],$value['ques_five']);
//            $value['zongfen'] = $sum;
        }
        unset($value);
        View::assign('scoreList',$scoreList);
        return View::fetch('score/index');
    }

    public function edit()
    {
        $score_id = Request::param('score_id');
        $validate = Validate::rule([
            'score_id|分数id' => 'require|between:1,'.PHP_INT_MAX,
        ]);

        if(!$validate->check(['score_id'=>$score_id])){
            echo $validate->getError();
            exit();
        }
        $scoreList = scoreModel::where('score_id','=',$score_id)->find();

        View::assign('scoreList',$scoreList);
        return View::fetch();
    }

    public function editSave()
    {
        $params = Request::param();
        $validate = Validate::rule([
            'score_id|分数id' => 'require|between:1,'.PHP_INT_MAX,
            'title_id|问卷主题id' => 'require',
            'user_id|用户id' => 'require',
            'ques_one|选项1' => 'require',
            'ques_two|选项2' => 'require',
            'ques_three|选项3' => 'require',
            'ques_four|选项4' => 'require',
            'ques_five|选项5' => 'require',
        ]);

        if(!$validate->check($params)){
            echo $validate->getError();
            exit();
        }

        $params["update_time"] = time();

        $result = scoreModel::update($params);

        if ($result) {
            echo "<script>alert('编辑成功');</script>";
            echo "<script>location.href='/index.php?s=admin/score/index'</script>";
        } else {
            echo "<script>alert('编辑失败,请联系管理员：1292888678@qq.com');</script>";
        }
    }

    public function delete()
    {
        $score_id = Request::param('score_id');
        $validate = Validate::rule([
            'score_id|分数id' => 'require|between:1,'.PHP_INT_MAX,
        ]);

        if(!$validate->check(['score_id'=>$score_id])){
            echo $validate->getError();
            exit();
        }
        $result = scoreModel::destroy($score_id);

        if ($result) {
            echo "<script>alert('删除成功');</script>";
            echo "<script>location.href='/index.php?s=admin/score/index'</script>";
        } else {
            echo "<script>alert('删除失败,请联系管理员：1292888678@qq.com');</script>";
        }
    }
}